# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json

from django.db.models import Q
from django.http import Http404, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from mock.models import MockData


class MockView(View):
    queryset = MockData.objects.all()

    def get(self, *args, **kwargs):
        route = '/' + kwargs.get('api')
        try:
            data = self.queryset.get(Q(route=route) & Q(enable=True)).return_data.encode("utf-8")
        except MockData.DoesNotExist:
            raise Http404("请求地址出错")
        try:
            res = json.loads(data, strict=False)
        except ValueError:
            raise Http404("json格式不支持")
        return JsonResponse(res, safe=False)

    def post(self, *args, **kwargs):
        route = '/' + kwargs.get('api')
        try:
            data = self.queryset.get(Q(route=route) & Q(enable=True)).return_data.encode("utf-8")
        except MockData.DoesNotExist:
            raise Http404("请求地址出错")
        try:
            res = json.loads(data, strict=False)
        except ValueError:
            raise Http404("json格式不支持")
        return JsonResponse(res, safe=False)
